<script src="__PUBLIC__/Static/libs/avalon/avalon.shim.min.js" charset="utf-8"></script>
<script src="__PUBLIC__/Static/js/district.js" charset="utf-8"></script>
<link rel="stylesheet" href="http://cdn.bootcss.com/font-awesome/4.2.0/css/font-awesome.min.css">
<style type="text/css">
	.area-group{
	    border-bottom: #eee solid 1px;
	}
	.area-group dd{
	    float: left;
	    width: 16.6667%;
	    padding-right: 10px;
	}
	.area-group dt label{
	    font-weight: bold;
	}
	.prov-item{
	    display: inline-block;
	    width: 24%;
	    margin-right: 1%;
	}
	.area-group .disabled{
	    color: #ccc;
	}
</style>
<div ms-controller="deliveryTemplate">
	<form action="" method="post" class="form-horizontal" id="mainForm">

		<div class="form-group">
			<label for="" class="col-sm-1 control-label">模板名称</label>
			<div class="col-sm-8">
				<input type="text" ms-duplex="presetJson.name" class="form-control" placeholder="请在此输入模板名称" />
			</div>
		</div>

		<div class="form-group">
			<label for="" class="col-sm-1 control-label">发货地址</label>
			<div class="col-sm-2">
				<select ms-duplex="presetJson.provCode" ms-change="$showCity" class="form-control">
				    <option value="0">==省份==</option>
				    <option ms-repeat="districtJson" ms-attr-value="$key" ms-attr-selected="$key==presetJson.provCode">{{ $val.name }}</option>
				</select>
			</div>
			<div class="col-sm-2">
				<select ms-duplex="presetJson.cityCode" ms-change="$showArea" class="form-control">
                    <option value="0">==城市==</option>
                    <option ms-repeat="locAddr.cities" ms-attr-value="$key" ms-attr-selected="$key==presetJson.cityCode">{{ $val.name }}</option>
				</select>
			</div>
			<div class="col-sm-2">
				<select ms-duplex="presetJson.areaCode" class="form-control">
				     <option value="0">==地区==</option>
				     <option ms-repeat="locAddr.areas" ms-attr-value="$key" ms-attr-selected="$key==presetJson.areaCode">{{ $val.name }}</option>
				</select>
			</div>
			<div class="col-sm-4">
				<div class="input-group">
					<div class="input-group-addon">详细地址</div>
					<input type="text" ms-duplex="presetJson.address" class="form-control" />
				</div>
			</div>
		</div>

		<div class="form-group">
			<label for="" class="col-sm-1 control-label">运送方式</label>
			<div class="col-sm-10">
				<div class="panel panel-default" ms-repeat="presetJson.list">
					<div class="panel-heading">
						<h4 class="panel-title"><label style="font-weight: normal"><input type="checkbox" ms-duplex-checked="$val.enabled" /> {{ $getExpressName($key) }}</label></h4>
					</div>
					<div class="panel-body" ms-if="$val.enabled">
						<h5><strong>设置运费方案</strong></h5>
						<table class="table table-condensed table-bordered">
							<thead>
								<tr>
									<th>运送地区</th>
									<th>初始件数</th>
									<th>初始运费(元)</th>
									<th>续件数量</th>
									<th>续件费用(元)</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
							    <tr>
							        <td class="col-sm-5">
							            <span class="label label-success prov-item">默认运费方案</span>
							        </td>
                                    <td>
                                        <input type="number" ms-duplex="$val.start" class="form-control" />
                                    </td>
                                    <td>
                                        <input type="number" ms-duplex="$val.postage" class="form-control" />
                                    </td>
                                    <td>
                                        <input type="number" ms-duplex="$val.plus" class="form-control" />
                                    </td>
                                    <td>
                                        <input type="number" ms-duplex="$val.postageplus" class="form-control" />
                                    </td>
                                    <td>
                                        <button class="btn btn-sm" disabled="disabled"><i class="fa fa-star"></i> 默认</button>
                                    </td>
							    </tr>
								<tr ms-repeat-item="$val.special">
									<td class="col-sm-5">
										<div><span ms-repeat-code="item.provCodes" class="label label-info prov-item">{{ $getProvName(code) }}</span></div>
										<div class="pull-right margin-top"><a class="btn btn-xs btn-warning" href="javascript:void(0)" ms-click="$editProvince($key,$index)"><i class="fa fa-edit"></i> 编辑</a>
										</div>
									</td>
									<td>
										<input type="number" class="form-control" ms-duplex="item.start" />
									</td>
									<td>
										<input type="number" class="form-control" ms-duplex="item.postage" />
									</td>
									<td>
										<input type="number" class="form-control" ms-duplex="item.plus" />
									</td>
									<td>
										<input type="number" class="form-control" ms-duplex="item.postageplus" />
									</td>
									<td><a href="javascript:void(0)" class="btn btn-danger btn-sm" ms-click="$remove"><i class="fa fa-times-circle"></i> 删除</a>
									</td>
								</tr>
							</tbody>
							<tfoot>
								<tr>
									<td colspan="6">
										<button class="btn btn-primary btn-sm" ms-click="$addSpecial($key)"><i class="fa fa-plus-circle"></i> 添加地区运费方案</button>
									</td>
								</tr>
							</tfoot>
						</table>
					</div>
				</div>
			</div>
		</div>
		
        <div class="form-group">
            <div class="col-sm-2"></div>
            <div class="col-sm-10">
            	<input type="hidden" name="id" ms-duplex="presetJson.id" value="" />
                <button class="btn btn-default" onclick="javascript: history.back()">返回上页</button>
                <button class="btn btn-default" onclick="javascript: location.href=document.referrer">返回上页并刷新</button>
                <button type="submit" class="btn btn-primary" ms-click="submitForm">提交保存</button>
                <span id="submitMsg" class="label"></span>
            </div>
        </div>

	</form>
	
	<!--弹出窗口-->
    <div class="modal fade" id="editProvinceModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    	<div class="modal-dialog modal-lg">
    		<div class="modal-content">
    			<div class="modal-header">
    				<h4 class="modal-title" id="myModalLabel">选择地区</h4>
    			</div>
    			<div class="modal-body">
                    <dl ms-repeat="areaGroup" class="area-group clearfix">
                        <dt class="checkbox"><label><!--<input type="checkbox" ms-duplex="groupSelected" ms-attr-value="el.title" >-->{{el.title}}</label></dt>
                        <dd ms-repeat-item="el.codes" class="checkbox"><label ms-class-disabled="checkDisabled(item)"><input type="checkbox" ms-duplex="provSelected" ms-attr-value="item" ms-attr-disabled="checkDisabled(item)">{{ $getProvName(item) }}</label></dd>
                    </dl>
                    <div class="margin-top">已选地区： <span ms-repeat="provSelected" class="label label-success margin-right">{{ $getProvName(el) }}</span></div>
    			</div>
    			<div class="modal-footer">
    				<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
    				<button type="button" class="btn btn-success" ms-click="$editProvSubmit">确定</button>
    			</div>
    		</div>
    	</div>
    </div>
</div>


<!--var districtJson = {
    "110000": {
        "name": "\u5317\u4eac\u5e02",
        "citys": {
            "110100": {
                "name": "\u5e02\u8f96\u533a",
                "code": "110100",
                "areas": {
                    "110101": {
                        "name": "\u4e1c\u57ce\u533a",
                        "code": "110101"
                    },
                    "110102": {
                        "name": "\u897f\u57ce\u533a",
                        "code": "110102"
                    },
                    "110103": {
                        "name": "\u5d07\u6587\u533a",
                        "code": "110103"
                    },-->


<!--*  
     * 'name' => "",
     * 'provCode' => '',
     * 'cityCode' => '',
     * 'areaCode' => '',
     * 'address' => '',
     * 'list' => array(
     *      '1' => array(
     *          'enabled' => true,
     *          'delivery' =>  'express',
     *          'start' => 1,
     *          'postage' => '',
     *          'plus' => 1,
     *          'postageplus' => '',
     *          'special' => array(
     *              0 => array(
     *                  'provCodes' => array(
     *                      1000,1001
     *                  ),
     *                  'start' => 1,
     *                  'postage' => '',
     *                  'plus' => 1,
     *                  'postageplus' => '',
     *              )
     *          )
     *      ),
     *      ... ...
     *   )
     * )-->

<script type="text/javascript">
	// 快递方法
	var methods = {: json_encode($methods) };

	// 运费模板数据
	var presetJson = {$presetJson};
	presetJson.name = presetJson.name || '';
	presetJson.address = presetJson.address || '';
	presetJson.provCode = presetJson.provCode || 0;
    presetJson.cityCode = presetJson.cityCode || 0;
    presetJson.areaCode = presetJson.areaCode || 0;
	
	// 地区关联数组
	var locList = districtJson;
	var locCities = districtJson[presetJson.provCode]? districtJson[presetJson.provCode]['citys']: {};
	var locAreas = locCities[presetJson.cityCode] ? locCities[presetJson.cityCode]['areas'] : {};
	
	// 地区
	var areaGroup = {$areaGroup};

	// 默认模板配置
	var getDefaultConfig = function(method) {
		return {
			enabled: false,
			delivery: method,
			start: 1,
			postage: 8,
			plus: 1,
			postageplus: 3,
			special: []
		}
	}

	// 处理运费模板数据
	if ($.type(presetJson.list) == 'array') {
		presetJson.list = {};
	}
	$.each(methods, function(index, val) {
		if (!presetJson['list'][index]) {
			presetJson['list'][index] = getDefaultConfig(val.tag);
		}
	});

	var vm = avalon.define({
		$id: 'deliveryTemplate',
		$districtJson: locList,
		locAddr: {
		    cities:locCities,
		    areas:locAreas
		},
		presetJson: presetJson,
		areaGroup: areaGroup,
		provSelected: [],
		provAllSelected: [],
		groupSelected: [],
		errorMsg: [],
		$getProvName: function(code) {
            return locList[code]['name'];
        },
		$getExpressName: function(key) {
			return methods[key]['name'];
		},
		$addSpecial: function(key) {
			vm.presetJson['list'][key]['special'].push({
				provCodes: [],
				start: 1,
				postage: 8,
				plus: 1,
				postageplus: 3
			})
		},
		editKey: '',
		editIndex: '',
		$editProvince: function(key,index) {
		    vm.editKey = key;
		    vm.editIndex = index;
		    var special = vm.presetJson['list'][vm.editKey]['special'];
		    vm.provSelected = special[vm.editIndex]['provCodes'];
		    vm.provAllSelected = [];
		    $.each(special, function(i,obj) {    
		    	if(i != vm.editIndex){
    		    	$.each(obj.provCodes, function(k,code) {    
    		    		    vm.provAllSelected.push(code)  
    		    	});                                                         
                }                                                       
		    });
			$('#editProvinceModal').modal();
		},
		$editProvSubmit: function(){
		    vm.presetJson['list'][vm.editKey]['special'][vm.editIndex]['provCodes'] = vm.provSelected;
		    $("#editProvinceModal").modal("hide");
		},
		checkDisabled: function(code){
		    return $.inArray(code, vm.provAllSelected)!=-1;
		},
		$showCity: function() {
		    if (this.value != 0) {
    		    vm.locAddr.cities = locList[this.value]['citys'];
		    } else {
		        vm.locAddr.cities = {};
		    }
	        vm.presetJson.cityCode = vm.presetJson.areaCode = 0;
		    vm.locAddr.areas = {};
		},
		$showArea: function() {
		    if (this.value != 0) {
                vm.locAddr.areas = vm.locAddr.cities[this.value]['areas'];
            } else {
                vm.locAddr.areas = {};
            }
            vm.presetJson.areaCode = 0;
        },
        submitForm: function(){
            $btnSubmit = $(this);
            var data = vm.presetJson.$model;
            $.ajax({
            	type:"POST",
            	url:"__CONTROLLER__/save",
            	async:true,
            	data: {
            		id: data.id,
            	    name: data.name,
            	    provCode: data.provCode,
            	    cityCode: data.cityCode,
            	    areaCode: data.areaCode,
            	    address: data.address,
            	    list: JSON.stringify(data.list)
            	},
            	beforeSend: function(){
            	    $btnSubmit.data("value", $btnSubmit.html()).html("<i class='fa fa-spin fa-spinner'></i> 正在提交中……").attr("disabled",true);
            	},
            	success: function(data){
            	  $("#submitMsg").html(data.msg).removeClass().addClass(['label label-success','label label-danger'][data.error]).show().delay(3000).fadeOut('slow');
            	},
            	error: function(error){
            	    $("#submitMsg").html(error).removeClass().addClass("label label-danger");
            	},
            	complete: function(){
            	    $btnSubmit.removeAttr("disabled").html($btnSubmit.data("value"));
            	}
            });
        }
	})
</script>

